package cn.tianya.irock.view;

import javax.servlet.http.Cookie;

import cn.tianya.framework.util.CookieUtil;
import cn.tianya.irock.bll.Roles;
import cn.tianya.irock.bll.Users;
import cn.tianya.irock.core.Page;
import cn.tianya.irock.data.model.User;
import cn.tianya.irock.enums.ApplicationExceptionType;
import cn.tianya.irock.enums.CreateUserStatus;
import cn.tianya.irock.exceptions.ApplicationException;

public class RegisterPage extends Page {

	@Override
	public void initial() {
		// TODO Auto-generated method stub

	}

	@Override
	public void show() {
		Cookie[] cookies = request.getCookies();
		String username = CookieUtil.getCookieValue(cookies, "user", "w");
		String key = CookieUtil.getCookieValue(cookies, "temp", "k");
		int intKey = key.length() == 0 ? 0 : Integer.parseInt(key);

		if (intKey != 0) {
			User user = new User();
			user.setUsername(username);
			
			CreateUserStatus status = Users.create(user);
			
			if (status == CreateUserStatus.Created) {
				response.setRedirect(config.getAppRoot() + config.getSiteUrls().getRawUrl(request.getSite(), "login.login").rawPath());
			} else if (status == CreateUserStatus.DuplicateUsername) {
				throw new ApplicationException(ApplicationExceptionType.UserInvalidCredentials);
			} else {
				throw new ApplicationException(ApplicationExceptionType.UnknowError);
			}
		}
		else
		{
			throw new ApplicationException(ApplicationExceptionType.UserInvalidCredentials);
		}
	}

}
